<template>
  <div class="product-classify-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <a-breadcrumb separator="/">
        <a-breadcrumb-item
            v-for="(item, index) in breadcrumb"
            :key="index"
            @click="item.type === 1 ? handleBreadcrumbClick(item.classify_url) : null"
            style="cursor: pointer">
          <a target="_self" :title="item.classify_name">{{ decodeHtmlEntities(item.classify_name) }}</a>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="product-classify-content">
      <!-- 左侧筛选条件 - 小屏幕下显示的筛选按钮 -->
      <a-button
        class="filter-toggle-btn"
        @click="showFilterDrawer = true"
        v-if="isSmallScreen"
      >
        <filter-outlined /> Filter Products
      </a-button>

      <!-- 左侧筛选抽屉 - 小屏幕下使用 -->
      <a-drawer
        v-if="isSmallScreen"
        title="Filter Products"
        placement="left"
        :visible="showFilterDrawer"
        @close="showFilterDrawer = false"
        :width="300"
      >
        <div class="filter-sidebar">
          <div class="category-section" v-if="classifyChain.length > 0">
            <h3 class="category-title">Category</h3>
            <a-collapse v-model:activeKey="activeKey" :bordered="false" ghost expandIcon-position="right">
              <a-collapse-panel key="1" header="Apparel">
                <div class="subcategory-list" v-for="(chain,index) in classifyChain" :key="index">
                  <div class="subcategory-item">
                    <a :href="`/classify/${chain.url}-${chain.id}.html`" target="_self" :title="chain.name">{{ chain.name }}</a>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>

          <div class="filter-section">
            <h3 class="filter-title">Filter</h3>
            <div class="filter-count">{{ totalProducts }} Styles</div>

            <!-- 已选择的筛选条件 -->
            <div v-if="selectedFilters.length > 0" class="selected-filters">
              <div v-for="(filter, index) in selectedFilters" :key="index" class="filter-tag">
                <a-tag closable @close="removeFilter(filter)">
                  {{ filter.value }}
                </a-tag>
              </div>
              <div class="clear-all" v-if="showClearAll">
                <a @click="clearAllFilters">Clear all</a>
              </div>
            </div>
          </div>

          <!-- 动态渲染筛选条件 -->
          <div v-for="(category, categoryIndex) in categoriesList" :key="categoryIndex" class="filter-category-section">
            <a-collapse v-model:activeKey="filterKeys[category.classify_id]" :bordered="false" ghost expandIcon-position="right">
              <a-collapse-panel :key="category.classify_id" :header="category.classify_name">
                <div class="filter-options filter-content-padding">
                  <a-radio-group
                    v-if="category.classify_name !== 'Features'"
                    v-model:value="filterValues[category.classify_id]"
                    class="filter-option-vertical"
                    @change="e => handleRadioChange(category.classify_id, category.classify_name, e)"
                  >
                    <a-radio
                      v-for="value in category.values"
                      :key="value.classify_value_id"
                      :value="value.classify_value_id"
                    >
                      {{ value.classify_value_name }}
                    </a-radio>
                  </a-radio-group>
                  <a-checkbox-group
                    v-else
                    v-model:value="filterMultiValues[category.classify_id]"
                    class="filter-option-vertical"
                    @change="values => handleCheckboxChange(category.classify_id, category.classify_name, values)"
                  >
                    <a-checkbox
                      v-for="value in category.values"
                      :key="value.classify_value_id"
                      :value="value.classify_value_id"
                    >
                      {{ value.classify_value_name }}
                    </a-checkbox>
                  </a-checkbox-group>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </div>
      </a-drawer>

      <!-- 左侧筛选条件 - 大屏幕下显示 -->
      <div class="filter-container" v-if="!isSmallScreen" ref="filterContainer">
        <div class="filter-sidebar">
          <div class="category-section" v-if="classifyChain.length > 0">
            <h3 class="category-title">Category</h3>
            <a-collapse v-model:activeKey="activeKey" :bordered="false" ghost expandIcon-position="right">
              <a-collapse-panel key="1" header="Apparel">
                <div class="subcategory-list" v-for="(chain,index) in classifyChain" :key="index">
                  <div class="subcategory-item" @click="handleSubcategoryClick(chain)">
                    <a :href="`/classify/${chain.url}-${chain.id}.html`" target="_self" :title="chain.name">{{ chain.name }}</a>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>

          <div class="filter-section">
            <div style="display:flex;align-items: center;justify-content: space-between;">
              <h3 class="filter-title">Filter</h3>
              <div class="filter-count">{{ totalProducts }} Styles</div>
            </div>
            <!-- 已选择的筛选条件 -->
            <div v-if="selectedFilters.length > 0" class="selected-filters">
              <div v-for="(filter, index) in selectedFilters" :key="index" class="filter-tag">
                <a-tag closable @close="removeFilter(filter)">
                  {{ filter.value }}
                </a-tag>
              </div>
              <div class="clear-all" v-if="showClearAll">
                <a @click="clearAllFilters">Clear all</a>
              </div>
            </div>
          </div>

          <!-- 动态渲染筛选条件 -->
          <div v-for="(category, categoryIndex) in categoriesList" :key="categoryIndex" class="filter-category-section">
            <a-collapse v-model:activeKey="filterKeys[category.classify_id]" :bordered="false" ghost expandIcon-position="right">
              <a-collapse-panel :key="category.classify_id" :header="category.classify_name">
                <div class="filter-options filter-content-padding">
                  <a-radio-group
                    v-if="category.classify_name !== 'Features'"
                    v-model:value="filterValues[category.classify_id]"
                    class="filter-option-vertical"
                    @change="e => handleRadioChange(category.classify_id, category.classify_name, e)"
                  >
                    <a-radio
                      v-for="value in category.values"
                      :key="value.classify_value_id"
                      :value="value.classify_value_id"
                    >
                      {{ value.classify_value_name }}
                    </a-radio>
                  </a-radio-group>
                  <a-checkbox-group
                    v-else
                    v-model:value="filterMultiValues[category.classify_id]"
                    class="filter-option-vertical"
                    @change="values => handleCheckboxChange(category.classify_id, category.classify_name, values)"
                  >
                    <a-checkbox
                      v-for="value in category.values"
                      :key="value.classify_value_id"
                      :value="value.classify_value_id"
                    >
                      {{ value.classify_value_name }}
                    </a-checkbox>
                  </a-checkbox-group>
                </div>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </div>
      </div>

      <!-- 右侧产品展示 -->
      <div class="products-container">
        <template v-if="loading">
          <!-- 骨架屏：产品列表骨架 -->
          <div class="products-header">
            <a-skeleton :paragraph="{ rows: 1 }" :title="{ width: '40%' }" active style="margin-bottom: 20px;" />
          </div>
          <div class="products-grid" :class="[`grid-${effectiveGridView}`]">
            <div v-for="i in pageSize" :key="i" class="product-card">
              <div class="product-image-container">
                <a-skeleton-image style="width:100%;aspect-ratio:3/4;" />
              </div>
              <div class="product-info">
                <a-skeleton :paragraph="{ rows: 2 }" :title="{ width: '80%' }" active />
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="products-header">
            <div class="products-title">
              {{ currentClassifyName }}
              <span class="products-count">({{ allProducts.length }} Styles)</span>
            </div>
            <div class="products-controls">
              <div class="sort-by">
                <span class="sort-label">Sort by</span>
                <a-dropdown>
                  <a class="sort-selector" @click.prevent>
                    {{ sortOptions.find(option => option.value === sortValue)?.label }}
                    <down-outlined />
                  </a>
                  <template #overlay>
                    <a-menu @click="(e) => handleSort(e.key)">
                      <a-menu-item v-for="option in sortOptions" :key="option.value">
                        {{ option.label }}
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
              <div class="view-selector">
                <span class="view-label" v-if="!isSmallScreen">View</span>
                <a-radio-group v-model:value="gridView" button-style="solid" size="small">
                  <a-radio-button value="2">2</a-radio-button>
                  <a-radio-button value="4" v-if="!isXsScreen">4</a-radio-button>
                  <a-radio-button value="6" v-if="!isSmallScreen">6</a-radio-button>
                </a-radio-group>
<!--                <span class="view-all-link" v-if="!isXsScreen">View all</span>-->
                <span class="page-indicator" v-if="!isXsScreen">
                  <left-outlined @click="prevPage" :disabled="currentPage === 1" />
                  <span>{{ currentPage }}</span> of <span>{{ totalPages }}</span>
                  <right-outlined @click="nextPage" :disabled="currentPage === totalPages" />
                </span>
              </div>
            </div>
          </div>

          <!-- 空状态提示 -->
          <div v-if="paginatedProducts.length === 0" class="empty-state">
            <div class="empty-state-icon">
              <img :src="SVG_ICONS.Empty" class="empty-icon-placeholder" alt="No products found" />
<!--            <div class="empty-icon-placeholder">-->
<!--              <inbox-outlined />-->
<!--            </div>-->
            </div>
            <h3 class="empty-state-title">No product found</h3>
<!--          <p class="empty-state-description">Please try adjusting your filter criteria or clearing all filters</p>-->
<!--          <a href="/" target="_self">-->
<!--            <a-button type="primary" class="clear-filters-btn">Home</a-button>-->
<!--          </a>-->
          </div>

          <!-- 商品列表 -->
          <div v-else class="products-grid" :class="[`grid-${effectiveGridView}`]">
            <div v-for="product in paginatedProducts" :key="product.id" class="product-card">
              <div class="product-image-container">
               <a :href="`/product/${product.url}.html`" :title="product.name">
                 <img
                     :src="product.images && product.images.length > 0 ? product.images[0] : ''"
                     :alt="product.name"
                     class="product-image"
                 />
               </a>
                <a :href="`/product/${product.url}.html`" :title="product.name">
                  <img
                      :src="product.images && product.images.length > 1 ? product.images[1] : product.images[0]"
                      :alt="product.name"
                      class="product-hover-image"
                  />
                </a>

                <div class="product-actions">
                  <a-button class="add-to-cart-btn" @click.stop="addCart(product)">Add +</a-button>
                </div>
              </div>
              <div class="product-info">
                <div class="product-name-container">
                  <div class="product-name">
                    <a :href="`/product/${product.url}.html`" target="_self" :title="product.name">{{ product.name }}</a>
                  </div>
                  <HeartFilled v-if="product.is_favorited == 1" @click.stop="toggleFavorite(product)"/>
                  <heart-outlined v-else class="wishlist-icon" :style="{ color: product.is_favorited ? '#ff4d4f' : '' }" @click.stop="toggleFavorite(product)"/>
                </div>
                <div class="product-price">
                  {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(product.min_price) }}
                  <span v-if="product.discount_enabled === 1" class="original-price">
                    {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(product.max_origin_price) }}
                  </span>
                  <span v-if="product.discount_enabled === 1" class="discount-tag">
                    {{ (100 - product.discount) }}% OFF
                  </span>
                </div>
                <div class="product-tags">
                  <span v-if="isNewProduct(product.create_time)" class="tag new-arrival">New arrival</span>
                  <span v-if="product.discount_enabled === 1" class="tag discount">
                    {{ (100 - product.discount) }}% OFF
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div class="pagination-container" v-if="paginatedProducts.length > 0">
            <a-pagination
              v-model:current="currentPage"
              :total="allProducts.length"
              v-model:pageSize="pageSize"
              :show-total="(total: number) => `Total ${total} items`"
              show-size-changer
              @showSizeChange="onShowSizeChange"
              @change="handlePageChange"
            />
          </div>
        </template>
      </div>
    </div>
  </div>

  <a-modal v-model:open="openDetail" width="1200px" title="Product Details" :footer="null">
    <ProductDetail.default v-if="openDetail && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, onUnmounted, watch, getCurrentInstance} from 'vue';
import { DownOutlined, HeartOutlined, LeftOutlined, RightOutlined, FilterOutlined, HeartFilled } from '@ant-design/icons-vue';
import { useWindowSize } from '@vueuse/core';
import * as ProductDetail from '@/components/ProductDetail.vue';
import {delFavorite, getClassifyAttributes, getFavoriteList} from "@/api/goods";
import {addFavorite} from "@/api/details"
import SVG_ICONS from "@/assets/SVG_ICONS.ts";
import {message} from "ant-design-vue";
import {Session} from "@/utils/storage.ts";
import {useRouter} from "vue-router";
import {getToken} from "@/utils/auth.ts";
import {useCartStore} from "@/store/cart.ts";
import emitter from '@/utils/eventBus';
import {useCurrencyStore} from "@/store/currency.ts";

// 公共变量
const router = useRouter();
const isLogin = ref(false)
const collectStore = useCartStore()
const { proxy } = getCurrentInstance()
const currencyStore = useCurrencyStore()
// 定义分类数据的接口类型
interface ClassifyValue {
  classify_value_id: number;
  classify_value_name: string;
}

interface ClassifyCategory {
  classify_id: number;
  classify_name: string;
  values: ClassifyValue[];
}

interface ClassifyChain {
  cn_name: string;
  create_time: string;
  delete_time: string;
  update_time: string;
  description: string;
  icon: string;
  keywords: string;
  name: string;
  title: string;
  url: string;
  display_type: number;
  id: number;
  manual_order: number;
  pid: number;
  status: number;
  weigh: number;
}

interface BreadcrumbItem {
  classify_name: string;
  classify_url: string;
  type: number;
}

// 定义商品数据接口
interface ProductAttribute {
  attribute_value_name: string;
}

interface Product {
  id: number;
  images: string[];
  max_origin_price: string;
  min_price: string;
  name: string;
  url: string;
  visit: number;
  heat: number;
  create_time: string;
  discount_enabled: number;
  discount: number;
  is_favorited: number;
  evaluate_count: number;
  attributes: ProductAttribute[];
}

interface BuyData {
  productId?: string | number;
  quantity?: number;
  [key: string]: any;
}
// 加入购物车
const openDetail = ref(false);
const goodId = ref<string | null>(null);

// 响应式相关
const { width } = useWindowSize();
const isSmallScreen = computed(() => width.value < 992);
const isXsScreen = computed(() => width.value < 768);

// ==================== 筛选相关 ====================
// 筛选条件的折叠面板状态
const activeKey = ref(['1']);
const filterKeys = ref<Record<number, string[]>>({});
const filterValues = ref<Record<number, number>>({});
const filterMultiValues = ref<Record<number, number[]>>({});

const showFilterDrawer = ref(false);
const filterContainer = ref<HTMLElement | null>(null);

// 存储原始商品列表和筛选后的商品列表
const productList = ref<Product[]>([]);
const allProducts = ref<Product[]>([]);
const displayProducts = ref<Product[]>([]);

// 新增 loading 状态
const loading = ref(true);

// 处理筛选条件变化
const handleFilterChange = (classifyId: number, classifyName: string, value: number) => {
  // 在已选择的筛选条件中查找相同类型的条件
  const index = selectedFilters.value.findIndex(filter => filter.type === classifyName);

  // 查找选中的值对应的名称
  const category = categoriesList.value.find(c => c.classify_id === classifyId);
  if (!category) return;

  const selectedValue = category.values.find(v => v.classify_value_id === value);
  if (!selectedValue) return;

  // 如果已经存在相同类型的条件，则更新它
  if (index !== -1) {
    selectedFilters.value[index] = {
      id: classifyId,
      valueId: value,
      type: classifyName,
      value: selectedValue.classify_value_name
    };
  } else {
    // 否则添加新的条件
    selectedFilters.value.push({
      id: classifyId,
      valueId: value,
      type: classifyName,
      value: selectedValue.classify_value_name
    });
  }

  // 应用筛选
  applyFilters();
};

// 处理多选筛选条件变化
const handleMultiFilterChange = (classifyId: number, classifyName: string, values: number[]) => {
  // 先移除该类型的所有已选项
  selectedFilters.value = selectedFilters.value.filter(filter => filter.type !== classifyName);

  // 查找选中的值对应的名称
  const category = categoriesList.value.find(c => c.classify_id === classifyId);
  if (!category) return;

  // 添加新选择的项
  values.forEach(valueId => {
    const selectedValue = category.values.find(v => v.classify_value_id === valueId);
    if (selectedValue) {
      selectedFilters.value.push({
        id: classifyId,
        valueId: valueId,
        type: classifyName,
        value: selectedValue.classify_value_name
      });
    }
  });

  // 应用筛选
  applyFilters();
};

// 应用筛选
const applyFilters = () => {
  // 重置当前页码
  currentPage.value = 1;

  // 应用本地筛选
  if (selectedFilters.value.length === 0) {
    // 重置所有商品
    allProducts.value = [...productList.value];
  } else {
    // 按属性类型分组筛选条件
    const filtersByType = selectedFilters.value.reduce((acc: any, filter: any) => {
      if (!acc[filter.type]) {
        acc[filter.type] = [];
      }
      acc[filter.type].push(filter);
      return acc;
    }, {});

    // 先筛选全部商品
    const filteredProducts = productList.value.filter(item => {
      // 检查每种类型的筛选条件
      return Object.entries(filtersByType).every(entry => {
        const [type, filters] = entry as [string, any[]];
        // 如果是价格区间
        if (type === 'Price Range') {
          return filters.some(filter => {
            const range = filter.value.split('-');
            const min = range[0] === 'Under' ? 0 : parseInt(range[0]);
            const max = range[1] === '∞' ? Infinity : parseInt(range[1]);
            return parseFloat(item.min_price) >= min &&
                (isNaN(max) ? true : parseFloat(item.max_origin_price) <= max);
          });
        }

        // 其他属性类型
        return filters.some(filter => {
          return item.attributes.some(attr =>
              attr.attribute_value_name === filter.value ||
              attr.attribute_value_name === decodeHtmlEntities(filter.value)
          );
        });
      });
    });

    // 更新筛选后的全部商品
    allProducts.value = filteredProducts;
  }

  // 更新商品总数
  totalProducts.value = allProducts.value.length;
};

// 已选择的筛选条件
const selectedFilters = ref<Array<{id: number, valueId: number, type: string, value: string}>>([]);
const showClearAll = computed(() => selectedFilters.value.length > 0);

// 监听筛选条件变化
watch(selectedFilters, (newFilters) => {
  // 可以根据筛选条件更新产品列表
  console.log('Filters changed:', newFilters);
  applyFilters();
}, { deep: true });

// 删除单个筛选条件
const removeFilter = (filter: {id: number, valueId: number, type: string, value: string}) => {
  // 从选中的单选按钮中移除
  if (filterValues.value[filter.id]) {
    delete filterValues.value[filter.id];
  }

  // 从选中的多选框中移除
  if (filterMultiValues.value[filter.id]) {
    const index = filterMultiValues.value[filter.id].indexOf(filter.valueId);
    if (index !== -1) {
      filterMultiValues.value[filter.id].splice(index, 1);
      // 如果数组为空，删除该属性
      if (filterMultiValues.value[filter.id].length === 0) {
        delete filterMultiValues.value[filter.id];
      }
    }
  }

  // 从已选择的筛选条件中移除
  selectedFilters.value = selectedFilters.value.filter(item =>
    !(item.id === filter.id && item.valueId === filter.valueId)
  );

  // 应用筛选
  applyFilters();
};

// 清除所有筛选条件
const clearAllFilters = () => {
  selectedFilters.value = [];
  filterValues.value = {};
  filterMultiValues.value = {};

  // 应用筛选
  applyFilters();
};

// 根据屏幕尺寸决定实际的网格布局
const gridView = ref('4');
const effectiveGridView = computed(() => {
  if (isXsScreen.value) return '2';
  if (isSmallScreen.value) return '3';
  return gridView.value;
});

// 每页显示的商品数量
const pageSize = ref(16);

// 总页数
const totalPages = computed(() => Math.ceil(allProducts.value.length / pageSize.value));

// 排序相关
const sortOptions = [
  {
    value: '0',
    label: 'Popular',
  },
  {
    value: '1',
    label: 'NEW',
  },
  {
    value: '2',
    label: 'Price low to high',
  },
  {
    value: '3',
    label: 'Price high to low',
  },
  {
    value: '4',
    label: 'Most Reviews',
  },
  {
    value: '5',
    label: 'Video',
  },
];

const sortValue = ref('0');

// 处理排序
const handleSort = (key: string) => {
  sortValue.value = key;
  // 本地排序逻辑
  switch (key) {
    case '0': // Popular
      allProducts.value.sort((a, b) => (b.visit || 0) - (a.visit || 0));
      break;
    case '1': // NEW
      allProducts.value.sort((a, b) => new Date(b.create_time).getTime() - new Date(a.create_time).getTime());
      break;
    case '2': // Price low to high
      allProducts.value.sort((a, b) => parseFloat(a.min_price || '0') - parseFloat(b.min_price || '0'));
      break;
    case '3': // Price high to low
      allProducts.value.sort((a, b) => parseFloat(b.min_price || '0') - parseFloat(a.min_price || '0'));
      break;
    case '4': // Most Reviews
      allProducts.value.sort((a, b) => (b.evaluate_count || 0) - (a.evaluate_count || 0));
      break;
    case '5': // Video
      // 假设带视频的商品在属性中有标记
      allProducts.value.sort((a, b) => {
        const hasVideoA = a.attributes.some(attr => attr.attribute_value_name === 'Video');
        const hasVideoB = b.attributes.some(attr => attr.attribute_value_name === 'Video');
        return hasVideoB ? 1 : hasVideoA ? -1 : 0;
      });
      break;
  }
  // 重置分页
  currentPage.value = 1;
};

// 分页功能
const currentPage = ref(1);
const handlePageChange = (page: number) => {
  currentPage.value = page;
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

const onShowSizeChange = (current: number, size: number) => {
  pageSize.value = size;
  currentPage.value = 1; // 切换每页条数时回到第一页
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value -= 1;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value += 1;
  }
};

// ======================== 收藏商品 ==========================
// 获取收藏列表
const getFavoriteListApi = async () => {
  await getFavoriteList().then(res => {
    if (res.code == 200) {
      emitter.emit('getFavoriteApi');
      // 触发新收藏事件
      emitter.emit('newFavorite');
      Session.set('collectList', res.result)
    } else {
      message.error(res.msg)
    }
  })
}
// 处理收藏功能
const toggleFavorite = async (product: any) => {
  if (isLogin.value) {
    // 登录状态
    if (product.is_favorited == 0) {
      await addFavorite({
        goods_id: product.id
      }).then(res => {
        if (res.code === 200) {
          message.success('Successfully collected');
          getFavoriteListApi()
          // 更新商品收藏状态
          product.is_favorited = 1
        } else {
          product.is_favorited = 0
          message.error(res.data.msg);
        }
      })
    } else {
      await delFavorite({
        goods_id: product.id
      }).then(res => {
        if (res.code === 200) {
          getFavoriteListApi()
          message.success('Cancel collection successfully');
          // 更新商品收藏状态
          product.is_favorited = 0
        } else {
          product.is_favorited = 1
          message.error(res.data.msg);
        }
      })

    }
  } else {
    // 未登录，提示登录
    message.warning('Please login first');
    router.push('/login');
  }
}
const updateViewListWithFavorites = () => {
  const cachedData = collectStore.getCollect()
  if (!cachedData || !Array.isArray(cachedData.data)) return

  productList.value = productList.value.map((item: any) => {
    // 在缓存数据中查找对应商品
    const cachedItem = cachedData.data.find((cached: any) => cached.goods_id === item.id)
    return {
      ...item,
      is_favorited: cachedItem ? 1 : item.is_favorited
    }
  })
}
// ==================== 面包屑 ====================
const breadcrumb = ref<BreadcrumbItem[]>([]);
const currentClassifyName = computed(() => {
  {
    if (!Array.isArray(breadcrumb.value) || breadcrumb.value.length === 0) {
      // 如果 breadcrumb 不是数组或为空，返回默认值
      return 'All'; // 根据实际需求替换默认值
    }
    const lastItem = breadcrumb.value[breadcrumb.value.length - 1];
    if (lastItem && typeof lastItem === 'object' && 'classify_name' in lastItem) {
      // 确保 lastItem 是对象且包含 classify_name 属性
      return lastItem.classify_name;
    }
    // 如果最后的元素不符合预期，返回默认值
    return 'All'; // 根据实际需求替换默认值
  }
})
const handleBreadcrumbClick = (url: string) => {
  if (url) {
    window.location.href = url;
  }
}
// 解码 HTML 实体（如 &amp; -> &）
const decodeHtmlEntities = (text: string) => {
  if (!text) return '';
  const textarea = document.createElement('textarea');
  textarea.innerHTML = text;
  return textarea.value;
}

// 获取当前页的商品
const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return allProducts.value.slice(start, end);
});

const totalProducts = ref(0);
const categoriesList = ref<ClassifyCategory[]>([]);
const classifyChain = ref<ClassifyChain[]>([]);

// 跳转分类页
const handleSubcategoryClick = (item:any) => {
  window.location.href = `/classify/${item.url}-${item.id}.html`;
}

// 获取商品列表接口
const getProductListApi = async () => {
  try {
    loading.value = true;
    // const classifyDetails = await getClassifyAttributes('0-4');
    const classifyDetails = (window as any).__INITIAL_CLASSIFY__.classifyDetails;
    if (!classifyDetails.goods || !Array.isArray(classifyDetails.goods)) {
      loading.value = false;
      return;
    }
    productList.value = classifyDetails.goods;
    updateViewListWithFavorites()
    allProducts.value = [...productList.value];
    breadcrumb.value = classifyDetails.attributes.breadcrumbs;
    totalProducts.value = classifyDetails.goods_count;
    categoriesList.value = classifyDetails.attributes.attributes || [];
    classifyChain.value = classifyDetails.attributes.classify_chain || [];
  } catch (error) {
    console.error('Error fetching product list:', error);
  } finally {
    loading.value = false;
  }
}

// 实现筛选栏粘性定位
const handleScroll = () => {
  if (!filterContainer.value || isSmallScreen.value) return;

  const containerRect = filterContainer.value.getBoundingClientRect();
  const windowHeight = window.innerHeight;
  const containerHeight = containerRect.height;

  // 如果筛选栏高度小于窗口高度，则固定在顶部
  if (containerHeight < windowHeight) {
    if (containerRect.top < 20) {
      filterContainer.value.style.position = 'fixed';
      filterContainer.value.style.top = '20px';
      filterContainer.value.style.width = filterContainer.value.offsetWidth + 'px';
    } else if (window.scrollY === 0) {
      filterContainer.value.style.position = 'static';
    }
  } else {
    // 如果筛选栏高度大于窗口高度，则使用原始布局流
    filterContainer.value.style.position = 'static';
  }
};

// 加入购物车
const addCart = (product: any) => {
  // 防止穿透点击
  if (openDetail.value) {
    return;
  }
  // 打开购买弹窗
  openDetail.value = true;

  goodId.value = String(product.id);
}
const handleBuy = (data?: BuyData) => {
  // message.success('The product has been successfully added to the cart, please go to the cart for settlement');
  openDetail.value = false;
};

// 在script部分添加新的处理函数
const handleRadioChange = (classifyId: number, classifyName: string, e: any) => {
  handleFilterChange(classifyId, classifyName, e.target.value);
};

const handleCheckboxChange = (classifyId: number, classifyName: string, values: any[]) => {
  handleMultiFilterChange(classifyId, classifyName, values);
};

// 添加新的方法判断是否为新品（例如30天内发布的商品）
const isNewProduct = (createTime: string) => {
  if (!createTime) return false;
  const productDate = new Date(createTime);
  const currentDate = new Date();
  const diffTime = currentDate.getTime() - productDate.getTime();
  const diffDays = diffTime / (1000 * 3600 * 24);
  return diffDays <= 30; // 30天内发布的视为新品
};

watch([gridView, isSmallScreen, isXsScreen], () => {
  if (isXsScreen.value) pageSize.value = 6;
  else if (isSmallScreen.value) pageSize.value = 9;
  else pageSize.value = parseInt(gridView.value) * 4;
});

onMounted(() => {
  // 检测是否登录
  if (getToken()) {
    isLogin.value = true
  }
  getProductListApi();
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

</script>

<style scoped lang="scss">
/* 筛选标签样式 */
.selected-filters {
  margin: 15px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.filter-tag {
  display: inline-block;
}

.clear-all {
  margin-left: 10px;
  color: #006400;
  font-weight: 500;
  cursor: pointer;

  a {
    color: #006400;
    text-decoration: underline;
  }
}

/* 筛选面板内容样式 */
.filter-content-padding {
  padding-left: 20px;
}

.filter-option-vertical {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.subcategory-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-left: 20px;
}

/* 覆盖Ant Design标签样式 */
:deep(.ant-tag) {
  margin-right: 0;
  padding: 5px 10px;
  border-color: #ddd;
  display: flex;
  align-items: center;
}

:deep(.ant-tag .anticon-close) {
  margin-left: 8px;
  color: #666;
}

.product-classify-container {
  max-width: 1920px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb-container {
  margin-bottom: 20px;
}

.product-classify-content {
  display: flex;
  gap: 30px;
  position: relative;
}

/* 左侧筛选区域样式 */
.filter-container {
  width: 220px;
  flex-shrink: 0;
  position: sticky;
  top: 20px;
  height: fit-content;
  align-self: flex-start;
}

.filter-toggle-btn {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.category-title,
.filter-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
}

.subcategory-item {
  cursor: pointer;
  font-size: 14px;
  padding: 3px 0;
}

.subcategory-item.active {
  font-weight: 600;
}

.filter-count {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.filter-section {
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
  padding-bottom: 10px;
}

.color-section,
.size-section,
.price-section,
.percentage-section,
.features-section {
  margin-bottom: 10px;
}

.price-slider {
  padding: 10px 0;
}

.price-range-display {
  margin-top: 10px;
  font-size: 14px;
}

/* 右侧产品区域样式 */
.products-container {
  flex: 1;
}

.products-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.products-title {
  font-size: 16px;
  font-weight: 700;
}

.products-count {
  color: #666;
  font-size: .75rem;
  display: inline-block;
  margin-left: .5rem;
}

.products-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  //border-bottom: 1px solid #f0f0f0;
  //padding-bottom: 15px;
  gap: 30px;
  flex-wrap: wrap;
}

.sort-by {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-label {
  font-size: 14px;
  text-decoration: underline;
}

.sort-selector {
  display: flex;
  align-items: center;
  gap: 5px;
}

.view-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.view-label {
  font-size: 14px;
}

.view-all-link {
  font-size: 14px;
  cursor: pointer;
  margin-left: 10px;
  text-decoration: underline;
}

.page-indicator {
  margin-left: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.products-grid {
  display: grid;
  gap: 20px;
  margin-bottom: 30px;
}

.grid-2 {
  grid-template-columns: repeat(2, 1fr);
}

.grid-3 {
  grid-template-columns: repeat(3, 1fr);
}

.grid-4 {
  grid-template-columns: repeat(4, 1fr);
}

.grid-6 {
  grid-template-columns: repeat(6, 1fr);
}

.product-card {
  display: flex;
  flex-direction: column;
  position: relative;
}

.product-name-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 5px;
}

.product-name {
  font-size: 14px;

  &:hover {
    cursor: pointer;
  }
}

.product-actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  gap: 10px;
  opacity: 1;
  visibility: visible;
}

.product-image-container {
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;

  :deep(:where(.css-dev-only-do-not-override-12unj27).ant-skeleton.ant-skeleton-element .ant-skeleton-image) {
    width: 100%;
    height: 510px;
  }

  &:hover {
    cursor: pointer;
  }
}

.product-image {
  width: 100%;
  aspect-ratio: 3/4;
  object-fit: cover;
  transition: opacity 0.3s ease;
}

.product-hover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-image-container:hover .product-image {
  opacity: 0;
}

.product-image-container:hover .product-hover-image {
  opacity: 1;
}

.wishlist-icon {
  background-color: white;
  padding: 8px;
  border-radius: 50%;
  font-size: 16px;
  cursor: pointer;
}

.add-to-cart-btn {
  background-color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 12px;
}

.product-info {
  padding: 5px 0;
}

.product-price {
  font-weight: 600;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-weight: normal;
  font-size: 0.9em;
}

.discount-tag {
  color: #ff4d4f;
  font-size: 0.9em;
  font-weight: bold;
}

.product-tags {
  display: flex;
  gap: 10px;
}

.tag {
  padding: .125rem .5rem;
  border-radius: .6875rem;
  font-weight: 400;
  font-size: .75rem;
  letter-spacing: .03125rem;
  background-color: #f2f2f2;
  display: inline-block;
  margin: .3125rem .375rem .3125rem 0;
}

.new-arrival {
  color: #000000;
}

.discount {
  color: #ff4d4f;
}

.sustainable {
  color: #2c8d5b;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

// 覆盖 Ant Design 样式
:deep(.ant-collapse-header) {
  padding: 8px 0 !important;
  flex-direction: row-reverse !important;
}

:deep(.ant-collapse-expand-icon) {
  padding-right: 8px !important;
}

:deep(.ant-collapse-arrow) {
  right: 0 !important;
  left: auto !important;
}

:deep(.ant-collapse-content-box) {
  padding: 8px 0 15px 0 !important;
}

:deep(.ant-collapse-expand-icon span) {
  display: inline-block;
  width: 1em;
  height: 1em;
  line-height: 1;
}

:deep(.ant-collapse-expand-icon) :where(.anticon) {
  font-size: 12px;
}

:deep(.ant-radio-wrapper),
:deep(.ant-checkbox-wrapper) {
  margin-bottom: 8px;
}

/* 添加深色模式支持 */
:deep(.ant-select-selector) {
  border-radius: 4px !important;
}

:deep(.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
  background-color: #fff;
  border: 1px solid #d9d9d9;
}

:deep(.ant-select-focused:not(.ant-select-disabled).ant-select:not(.ant-select-customize-input) .ant-select-selector) {
  // border-color: #40a9ff;
  box-shadow: 0 0 0 1px #e0e0e0;
}

// 响应式样式
@media screen and (max-width: 1200px) {
  .products-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .products-controls {
    width: 100%;
  }
}

@media screen and (max-width: 1023px) {
  .product-classify-content {
    flex-direction: column;
  }

  .filter-container {
    display: none;
  }
}

@media screen and (max-width: 767px) {
  .products-controls {
    flex-direction: column;
    align-items: flex-start;
  }

  .sort-by, .view-selector {
    width: 100%;
  }
}

/* 自定义面包屑样式 */
:deep(.ant-breadcrumb) {
  margin: 0;
  color: #000000;
  font-size: 0.8rem;
  line-height: 1.5;
  letter-spacing: .5px;
  font-weight: 400;
}

:deep(.ant-breadcrumb a) {
  color: rgba(0, 0, 0, 0.9);
  transition: color 0.3s;
}

:deep(.ant-breadcrumb a:hover) {
  color: #000000;
  text-decoration: #000000;
  background-color: #FFFFFF;
}

:deep(.ant-breadcrumb-separator) {
  margin: 0 8px;
  color: rgba(0, 0, 0, 0.45);
}

:deep(.ant-breadcrumb > span:last-child) {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
}

/* 添加空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  //background-color: #fafafa;
  border-radius: 8px;
  margin: 50px 0;
}

.empty-state-icon {
  margin-bottom: 20px;
}

.empty-icon-placeholder {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  //background-color: #f5f5f5;
  margin: 0 auto;
  font-size: 40px;
  color: #bfbfbf;
}

.empty-state-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #333;
}

.empty-state-description {
  color: #666;
  margin-bottom: 20px;
  max-width: 400px;
}

.empty-state a-button {
  margin-top: 10px;
}
</style>
